package tuan.score;

import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;

public class FontSizeScore extends NodeScore {
	String op;
	int size;
	double score;

	public FontSizeScore(int size, String op, double score) throws Exception {
		this.score = score;
		this.op = op;
		this.size = size;
	}

	@Override
	protected double getScore(Node node) {
		double defaultScore = 0.0;
		int value = -1;
		while (node != null && value == -1) {
			value = getSize(node);
			node = node.getParentNode();
		}

		if (value != -1) {
			if (op.equals(">")) {
				return value > size ? score : defaultScore;
			}
			if (op.equals(">=")) {
				return value >= size ? score : defaultScore;
			}
			if (op.equals("<")) {
				return value < size ? score : defaultScore;
			}
			if (op.equals("<=")) {
				return value <= size ? score : defaultScore;
			}
			if (op.equals("!=")) {
				return value != size ? score : defaultScore;
			}
		}
		return defaultScore;
	}

	int getSize(Node node) {
		int size = -1;
		if (!node.hasAttributes()) {
			return size;
		}
		NamedNodeMap attrNodes = node.getAttributes();
		for (int i = 0; i < attrNodes.getLength(); i++) {
			Node attrNode = attrNodes.item(i);
			String attrName = attrNode.getNodeName().toLowerCase();
			try {
				if (attrName.equals("font-size")) {
					size = Integer.parseInt(attrNode.getNodeValue());
				}
				if (attrName.equals("style")) {
					String[] attrs = attrNode.getNodeValue().toLowerCase().split(";");
					for (String attr : attrs) {
						String[] attrMap = attr.split(":");
						if (attrMap.length == 2 && attrMap[0].equals("font-size")) {
							size = Integer.parseInt(attrMap[1].replace("px", ""));
							break;
						}
					}

				}
			} catch (Exception e) {

			}
		}
		return size;
	}
}
